var QueryProductRecord = function () {
  var template = /* html */ `
    <div class="query-product-record" v-loading.fullscreen.lock="loading">
      <search-btn-view btn-text="出入库查询" @before-open="resetSearch" @search="searchData">
        <template slot="append">
          <el-button v-if="approvalIds.length>0" type="primary" size="medium" @click="approvalWarehouseList">批量审核</el-button>
          <el-button v-if="invalidIds.length>0" type="primary" size="medium" @click="invalidWarehouseList">审核后退回</el-button>
          <el-button type="primary" size="medium" @click="print" v-if="printData.length>0">打印</el-button>
          <el-button type="primary" size="medium" @click="exportExcel">导出Excel</el-button>
        </template>
        <template slot="right">
          <table-col-show-select v-if="tableHideColumnKey!==null" :table-name="tableName" :hide-column.sync="tableHideColumnKey"></table-col-show-select>
        </template>
        <div slot="search-content">
          <record-search-form :search="search"></record-search-form>
        </div>
      </search-btn-view>

      <div class="query-product-record-table-div">
        <el-table fit stripe border ref="productWarehouseInoutRecord" :data="warehouseList" style="width:100%;" height="parent" @row-click="lookWarehouseInfo" :hide-column-keys="getTableHideColumns()">
          <checkbox-table-column width="70px" header-text="打印" check-field="id" :fixed="true" @select-change="selectPrintData" key="printData" column-key="printData">
          </checkbox-table-column>
          <checkbox-table-column width="70px" header-text="审批" check-field="id" :fixed="true" :selectable="canApprovalMethod"
            @select-change="selectApproval" key="approvalData" column-key="approvalData">
          </checkbox-table-column>
          <checkbox-table-column v-if="hasAbolish" width="105px" header-text="审核后退回" check-field="id" :fixed="true" :selectable="canInvalidMethod"
            @select-change="selectInvalid" key="invalidData" column-key="invalidlData">
          </checkbox-table-column>
          <el-table-column sortable :resizable="false" prop="customerNo" :fixed="true" key="customerNo" label="客户型号" :auto-width="true"
            min-width="90px" header-align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="warehouseTypeText" key="warehouseTypeText" label="类型" min-width="70px" align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="typeText" key="typeText" label="来源" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="companyOrderId" key="companyOrderId" label="订单编号" :auto-width="true"
            min-width="90px" header-align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="factoryNo" key="factoryNo" label="工厂型号" :auto-width="true"
            min-width="90px" header-align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="customerName" key="customerName" label="客户名称" :auto-width="true"
            min-width="100px" header-align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="colorDescription" key="colorDescription" label="描述"
            :auto-width="true" min-width="90px" header-align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="inCountPrice" key="inCountPrice" label="单价" min-width="80px"
            align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="inOutUnit" key="inOutUnit" label="单位" min-width="80px" align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="count" key="count" label="数量" :auto-width="true" min-width="80px"
            align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="totalPrice" key="totalPrice" label="金额" min-width="140px"
            align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="selfOutFuCount" key="selfOutFuCount" label="交接数" :auto-width="true"
            min-width="80px" header-align="center">
            <div slot-scope="scope">
              <span v-if="scope.row.selfOutFuCount!==0">{{scope.row.selfOutFuCount}} 付</span>
            </div>
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="status" key="status" label="状态" min-width="80px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('warehouseInOutRecord.status.'+scope.row.status)}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="createUser" key="createUser" :auto-width="true" label="制单人"
            min-width="90px" header-align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="createTime" key="createTime" label="制单时间" width="105px" align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="approvalUser" key="approvalUser" label="审核人" :auto-width="true"
            min-width="90px" header-align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.status!==0">{{scope.row.approvalUser}}</span>
              <span v-else-if="scope.row.auditableUser.length===0">暂无审核人</span>
              <template v-else>
                <el-tooltip placement="top" :enterable="false">
                  <div slot="content">
                    {{scope.row.auditableUser.join(",")}}
                  </div>
                  <span>移入查看审核人</span>
                </el-tooltip>
              </template>
            </template>
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="approvalTime" key="approvalTime" label="审核时间" min-width="105px"
            align="center"></el-table-column>
          <el-table-column show-overflow-tooltip :resizable="false" prop="remark" key="remark" label="备注" min-width="200px" header-align="center">
          </el-table-column>
          
          <el-table-column auto-width label="操作" key="operation" min-width="60px" fixed="right" header-align="center">
            <template slot-scope="props" v-if="props.row.status===0">
              <template v-if="props.row.isApperval===1">
                <el-button class="table-btn" type="primary" size="mini" @click.stop="approvalWarehouse(props.row)">审核</el-button>
                <el-button class="table-btn" type="danger" size="mini" style="margin-left:0;" @click.stop="retreatWarehouse(props.row)">退回</el-button>
              </template>
              <template v-if="props.row.isCreate===1">
                <el-button v-if="[1,3,4,9].indexOf(props.row.type)===-1" class="table-btn" type="primary" size="mini" @click.stop="updateWarehouse(props.row)">修改</el-button>
                <el-button class="table-btn" type="danger" size="mini" style="margin-left:0;" @click.stop="deleteWarehouse(props.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange"></table-pagination>

      <el-dialog title="库存信息" :visible.sync="openWarehouseInfo" width="60%" top="5vh" @close="selectWarehouse=null">
        <div style="height:calc(90vh - 54px);overflow:auto">
          <warehouse-info v-if="openWarehouseInfo" :warehouse="selectWarehouse"></warehouse-info>
        </div>
      </el-dialog>

      <prompt-form title="修改出入库" :visible.sync="openUpdateForm" :option="warehouseOption" :data="selectWarehouse" width="400px"
        @close="selectWarehouse=null" @ensure="toUpdateWarehouse"></prompt-form>

      <el-dialog fullscreen class="dialog-fullscreen" :title="printTempl===null&&templateType==='in'?'入库单':'出库给客人打印'" :visible.sync="openPrintDialog">
        <div style="height:100%;overflow:auto">
          <template v-if="openPrintDialog">
            <template v-if="printTempl===null">
              <print-warehouse v-if="templateType==='out'" :records="printData"></print-warehouse>
              <print-in-warehouse v-else :records="printData"></print-in-warehouse>
            </template>
            <print-warehouse-template v-else :print-data="printData" :template="printTempl"></print-warehouse-template>
          </template>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    mixins: [
      printOrderMixin('inoutWarehouseOrder'),
      printWarehouseOrderTemplateMixin,
      tableColShowMixin('productWarehouseInoutRecord'),
      tablePaginationMixin()
    ],

    data: function () {
      var search = {
        orderId: '',
        companyOrderId: '',
        factoryNo: '',
        customerNo: '',
        customerName: '',
        createUser: '',
        type: '',
        queryType: '',
        startDate: null,
        endDate: null,
        status: 0,
        source: ''
      };
      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        warehouseList: [],
        approvalIds: [],
        invalidIds: [],
        printData: [],
        openUpdateForm: false,
        openWarehouseInfo: false,
        hasAbolish: false,
        warehouseOption: {
          formItems: []
        },
        selectWarehouse: null,
        i18n: i18n,
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 10
        }
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setUser(),
        this.setWarehouseList(true, false)
      ]).then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          var hasAbolish;
          var isManager = user.isManager;
          if (isManager === 1) {
            hasAbolish = true;
          } else {
            var inOutReturnUser = _.get(user, 'companyInfo.inOutReturnUser');
            hasAbolish = inOutReturnUser === user.userId;
          }
          self.hasAbolish = hasAbolish;
          return user;
        });
      },

      setWarehouseList: function (isSearch, hasLoading) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        if (hasLoading === undefined) {
          hasLoading = true;
        }

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize
        };
        this.setPostData(postData);

        if (hasLoading) {
          this.loading = true;
        }
        var self = this;
        ajaxRequest("warehouse/getWarehouseInOutDetaliList", postData, false).then(function (res) {
          var warehouseList = res.returnData;
          if (warehouseList.length === 0 && pagination.currentPage !== 1) {
            self.pagination.totalCount = res.iTotalRecords;
            self.setWarehouseList(isSearch);
            return;
          }

          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          for (var i = 0; i < warehouseList.length; i++) {
            var warehouse = warehouseList[i];
            if ([1, 3].indexOf(warehouse.source) !== -1 || [1, 3, 4, 7, 8, 11].indexOf(warehouse.type) !== -1) {
              warehouse.warehouseTypeText = "入库";
            } else {
              warehouse.warehouseTypeText = "出库";
            }

            var totalPrice = warehouse.inOutMoney;
            if (SysUtil.isEmpty(totalPrice) || totalPrice === 0) {
              var inCountPrice = warehouse.inCountPrice;
              var count = warehouse.count;
              if (SysUtil.isEmpty(inCountPrice) || SysUtil.isEmpty(count)) {
                totalPrice = 0;
              } else {
                totalPrice = inCountPrice * count;
                totalPrice = _.round(totalPrice, 2);
              }
            }
            warehouse.totalPrice = totalPrice;

            if (warehouse.auditableUser === null) {
              warehouse.auditableUser = [];
            }
          }

          self.warehouseList = warehouseList;
          self.pagination.totalCount = res.iTotalRecords;
          self.printData = [];
          self.approvalIds = [];
          self.invalidIds = [];

          if (hasLoading) {
            self.loading = false;
          }
        }).catch(function () {
          if (hasLoading) {
            self.loading = false;
          }
        });
      },

      exportExcel: function () {
        this.search = _.cloneDeep(this.oldSearch);
        var postData = {};
        this.setPostData(postData);
        var formParam = SysUtil.formatFormParam(postData);
        var basePath = SysUtil.getBasePath();
        var path = `${basePath}/warehouse/exportExcelFileByWarehouse?${formParam}`;
        window.open(path);
      },

      setPostData(postData) {
        var search = this.search;
        var fields = ['orderId', 'companyOrderId', 'factoryNo', 'customerNo', 'customerName', 'createUser', 'type', 'queryType', 'status',
          'source'
        ];
        SysUtil.setPostData(postData, search, fields);
        if (search.startDate !== null) {
          postData.startDate = moment(search.startDate).format('YYYY-MM-DD');
        }
        if (search.endDate !== null) {
          postData.endDate = moment(search.endDate).format('YYYY-MM-DD');
        }
        postData.warehouseType = 1;
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setWarehouseList(true);
      },

      pageChange: function () {
        this.setWarehouseList();
      },

      approvalWarehouse: function (warehouse) {
        var postData = {
          status: 1,
          id: warehouse.id,
          name: warehouse.createUser
        };
        this.toApprovalWarehouse(postData, "warehouse/approvalWarehouse");
      },

      approvalWarehouseList: function () {
        var ids = this.approvalIds;
        if (ids.length === 0) {
          this.$alert('请选择需要审核的记录', '信息');
          return;
        }

        ids = _.map(ids, function (id) {
          return {
            id: id
          };
        });

        var postData = {
          status: 1,
          ids: JSON.stringify(ids)
        };
        this.toApprovalWarehouse(postData, "warehouse/approvalAllWarehouse");
      },

      toApprovalWarehouse: function (postData, url) {
        this.loading = true;
        var self = this;
        ajaxRequest(url, postData).then(function (msg) {
          self.loading = false;
          if (msg.indexOf("重新确认") > -1) {
            self.$confirm('物料出库后,是否交接到车间', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              showClose: false,
              type: 'info'
            }).then(function () {
              postData.isTcy = 1;
              self.toApprovalWarehouse(postData, url);
            }).catch(function () {
              postData.isTcy = 2;
              self.toApprovalWarehouse(postData, url);
            });
          } else {
            self.$alert(msg, '信息', {
              callback: function () {
                self.setWarehouseList();
              }
            });
          }
        }).catch(function () {
          self.loading = false;
        });
      },

      retreatWarehouse: function (warehouse) {
        var self = this;
        this.$prompt('请输入退回理由', '提示', {
          inputValue: ''
        }).then(function (option) {
          var reason = option.value;
          if (reason === '') {
            reason = "退回";
          }
          self.toRetreatWarehouse(warehouse, reason);
        }).catch(function () {});
      },

      toRetreatWarehouse: function (warehouse, reason) {
        var postData = {
          status: 2,
          id: warehouse.id,
          name: warehouse.name,
          approvalReason: reason
        };
        this.loading = true;
        var self = this;
        ajaxRequest("warehouse/approvalWarehouse", postData).then(function (msg) {
          self.loading = false;
          self.$alert(msg, '信息', {
            callback: function () {
              self.setWarehouseList();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      updateWarehouse: function (warehouse) {
        if (warehouse.type === 7 || warehouse.source === 1) {
          this.$alert('请至我的报工页面修改', '提示');
          return;
        }

        var precision = SysUtil.getMaterialNumberPrecision(warehouse.inOutUnit, 4);
        var formItems = [{
          type: 'number',
          field: 'count',
          label: '出入库数量',
          isRequired: true,
          precision: precision,
          min: 1 / Math.pow(10, precision)
        }];

        var selfOutFuCount = warehouse.selfOutFuCount;
        if (selfOutFuCount !== 0) {
          formItems.push({
            type: 'number',
            field: 'selfOutFuCount',
            label: '交接数(付)',
            isRequired: true,
            precision: 0,
            min: 1
          });
        }

        this.warehouseOption.formItems = formItems;
        this.selectWarehouse = warehouse;
        this.openUpdateForm = true;
      },

      toUpdateWarehouse: function (inputData) {
        var postData = {};
        for (var key in inputData) {
          var value = inputData[key];
          if (value === undefined) {
            var msg = i18n.getMsg(`warehouseInOutRecord.error.${key}`);
            this.$alert(msg, '信息');
            return;
          }
          postData[key] = value;
        }

        var warehouse = this.selectWarehouse;
        var isSame = SysUtil.hasSameProperty(postData, warehouse);
        if (isSame) {
          this.openUpdateForm = false;
          this.$alert('出入库修改成功', '信息');
          return;
        }
        postData.id = warehouse.id;

        this.loading = true;
        var self = this;
        ajaxRequest("warehouse/updateWarehouse", postData).then(function () {
          self.loading = false;
          self.openUpdateForm = false;
          self.$alert('出入库修改成功', '消息', {
            callback: function () {
              self.setWarehouseList();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      deleteWarehouse: function (warehouse) {
        var type = warehouse.type;
        var source = warehouse.source;
        var msg;
        if (type === 7 || source === 1) {
          var warehouseName;
          if (source === 1) {
            warehouseName = warehouse.warehouse;
          } else {
            warehouseName = '仓库';
          }
          msg = `此记录为车间交接至${warehouseName}，删除将同时删除车间报工数据，是否要删除该条记录?`;
        } else {
          msg = '确定要删除该条记录吗?';
        }

        var self = this;
        this.$confirm(msg, '删除确认', {
          type: 'info'
        }).then(function () {
          self.toDeleteWarehouse(warehouse);
        }).catch(function () {});
      },

      toDeleteWarehouse: function (warehouse) {
        this.loading = true;
        var self = this;
        ajaxRequest("warehouse/deleteWarehouse", {
          id: warehouse.id
        }).then(function () {
          self.loading = false;
          self.$alert('出入库记录删除成功', '消息', {
            callback: function () {
              self.setWarehouseList();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      invalidWarehouseList: function () {
        var invalidIds = this.invalidIds;
        if (invalidIds.length === 0) {
          return;
        }

        var self = this;
        this.$confirm('是否确定退回这些选中的审核记录', '作废确认', {
          type: 'info'
        }).then(function () {
          self.toInvalidWarehouse(invalidIds);
        }).catch(function () {});
      },

      toInvalidWarehouse: function (invalidIds) {
        this.loading = true;
        var self = this;
        ajaxRequest('warehouse/toVoidInOutRecord', {
          idArray: JSON.stringify(invalidIds)
        }).then(function () {
          self.loading = false;
          self.$alert('成功退回所选中的审核记录', '消息', {
            callback: function () {
              self.setWarehouseList();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      selectPrintData: function (ids, data) {
        this.printData = data;
      },

      canApprovalMethod: function (row) {
        return row.isApperval === 1 && row.status === 0;
      },

      selectApproval: function (ids) {
        this.approvalIds = ids;
      },

      canInvalidMethod: function (row) {
        return row.status === 1;
      },

      selectInvalid: function (ids) {
        this.invalidIds = ids;
      },

      lookWarehouseInfo: function (warehouse, column) {
        var columnKey = column.columnKey;
        if (['printData', 'approvalData'].indexOf(columnKey) !== -1) {
          return;
        }

        this.selectWarehouse = warehouse;
        this.openWarehouseInfo = true;
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      RecordSearchForm: RecordSearchForm,
      CheckboxTableColumn: CheckboxTableColumn,
      PromptForm: PromptForm,
      WarehouseInfo: WarehouseInfo,
      PrintWarehouse: PrintWarehouse,
      PrintInWarehouse: PrintInWarehouse,
      PrintWarehouseTemplate: PrintWarehouseTemplate
    },

    template: template
  };
}();
